package com.xiaow.springsecuriydemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaow.springsecuriydemo.entity.Comments;
import com.xiaow.springsecuriydemo.entity.Trading;
import com.xiaow.springsecuriydemo.service.CommentsService;
import com.xiaow.springsecuriydemo.service.TradingService;
import com.xiaow.springsecuriydemo.utils.UserUtils;
import com.xiaow.springsecuriydemo.vo.CommentsVo;
import com.xiaow.springsecuriydemo.vo.LoginUser;
import com.xiaow.springsecuriydemo.vo.Result;
import com.xiaow.springsecuriydemo.vo.TradingVo2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiaow
 * @since 2022-09-19
 */
@RestController
@RequestMapping("/comments")
public class CommentsController {

    @Autowired
    CommentsService commentsService;
    @Autowired
    TradingService tradingService;

    /**
     * 根据商品id分页获取评论
     * @param page
     * @param limit
     * @param goodsid
     * @return
     */
    @GetMapping("/getCommentsByGoodsId")
    public Result getCommentsByGoodsId(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "limit", defaultValue = "10") Integer limit, @RequestParam(name = "goodsid") Long goodsid) {
        IPage<TradingVo2> p = new Page<>(page, limit);
        IPage<CommentsVo> commentsByGoodsId = commentsService.getCommentsByGoodsId(p, goodsid);
        return Result.succ(commentsByGoodsId);
    }


    @PostMapping("/addComments")
    @PreAuthorize("hasAuthority('/user')")
    public Result addComments(@RequestBody Comments comments){
        LoginUser user = UserUtils.getUser();
        Long goodsid = comments.getGoodsid();
//        判断用户是否购买过
        QueryWrapper<Trading> tradingQueryWrapper = new QueryWrapper<>();
        tradingQueryWrapper.eq("goodsid",comments.getGoodsid());
        tradingQueryWrapper.eq("userid",user.getUser().getId());
        List<Trading> list = tradingService.list(tradingQueryWrapper);
        if(list==null||list.size()==0)
            return Result.fail("只有购买过的用户才可以评价");
        comments.setCtime(LocalDateTime.now());
        comments.setUserid(user.getUser().getId());
        boolean save = commentsService.save(comments);
        if(save)
            return Result.succ("评价成功");
        return Result.succ("评价失败，请稍后重试");
    }







}
